package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.conf.WfNextStepVo;
import com.miplus.ccrm.core.controller.vo.action.StopCaseListVo;
import com.miplus.ccrm.core.mapper.ConContactMapper;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.pojo.ConContact;
import com.miplus.ccrm.core.pojo.FiCreditcases;
import com.miplus.ccrm.core.pojo.FiReturn;
import com.miplus.ccrm.core.pojo.FiStopcall;
import com.miplus.ccrm.core.mapper.FiStopcallMapper;
import com.miplus.ccrm.core.service.FiWorkFlowCase;
import com.miplus.ccrm.core.service.collect.FiTaskService;
import com.miplus.ccrm.core.service.strategy.CpCalllistService;
import com.miplus.ccrm.core.utils.EnumConfirmStatus;
import com.miplus.ccrm.core.utils.EnumFiCaseQueue;
import com.miplus.ccrm.core.utils.EnumFiChannel;
import com.miplus.ccrm.core.utils.EnumWorkFlowStep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* @author pc
* @description 针对表【fi_stopcall(号码停催表)】的数据库操作Service实现
* @createDate 2024-04-02 19:24:07
*/
@Slf4j
@Service
public class FiStopcallServiceImpl extends MPJBaseServiceImpl<FiStopcallMapper, FiStopcall>
    implements FiStopcallService{
    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private CpCalllistService cpCalllistService;
    @Resource
    private FiWorkFlowCase fiWorkFlowCase;
    @Resource
    private ConContactMapper conContactMapper;
    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;

    @Override
    public IPage<FiStopResVo> fiStopCallList(JSysUser user, FiStopReqVo paras)
    {
        String $usrid=user.getUsrid();
        Boolean phnDisStar= JUsrPerm.hasPermission(user,JUsrPerm.DISSTAR_PHN);
        String stoptype=paras.getStoptype();
        if(JPubUtils.IsNotEmpty(stoptype)){
            stoptype=stoptype.toUpperCase();
        }
        IPage<FiStopResVo> resVoIPage=selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                FiStopResVo.class,
                new MPJLambdaWrapper<FiStopcall>()
                        .selectAs("fun_getnames('FI.STOPCALL.STATUS',t.status)", FiStopResVo::getStatusdsc)
                        .selectAs("fun_getnames('FI.STOPCALL.TYPE',t.stoptype)", FiStopResVo::getStoptypedsc)
                        .selectAs("fun_getnames('FI.STOPCALL.REASON',t.reason)", FiStopResVo::getApplyreasondsc)
                        .selectAs("(select cl.wfid from cp_calllist cl where cl.clid=t.clid)", FiStopResVo::getWfid)
                        .selectAs("fun_getgrpname(t.applyusr)",FiStopResVo::getApplygrpname)
                        .selectAll(FiStopcall.class)
                        .apply("fc_hasApplyView(t.stopid,'SYS_STOPCALL',t.applyusr,{0},t.status,t.confirmusr)>0",$usrid)
                        .apply(JPubUtils.IsNotEmpty(paras.getApplygrp()),"fc_hasUsrInGroup(t.applyusr,{0})>0",paras.getApplygrp())
                        .eq(JPubUtils.IsNotEmpty(paras.getStopkey()),FiStopcall::getStopkey,paras.getStopkey())
                        .eq(JPubUtils.IsNotEmpty(stoptype),FiStopcall::getStoptype,stoptype)
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()),FiStopcall::getStatus,paras.getStatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getApplyusr()),FiStopcall::getApplyusr,paras.getApplyusr())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), FiStopcall::getApplydt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .orderByAsc(FiStopcall::getApplydt)
        );
        resVoIPage.convert(u->{
            if(!phnDisStar&&(!JPubUtils.IsEqual(u.getStoptype(),"CASE"))){
                u.setStopkey(JPubUtils.getStarString(JPubUtils.STAR_PHN,u.getStopkey()));
            }
            return u;
        });

        return resVoIPage;
    }

    @Override
    @Transactional
    public CmdResVo fiStopCallAdd(String $usrid, FiStopAddVo paras)
    {
        if(JPubUtils.IsEmpty(paras.getPhone())&&JPubUtils.IsEmpty(paras.getFicaseid())){
            throw new ServiceException(EnumRCode.ArgErr.value, EnumRCode.ArgErr.name);
        }
        String stopkey=paras.getPhone();
        if(JPubUtils.IsEqual(paras.getStoptype(),"CASE")){
            stopkey=paras.getFicaseid().toString();
        }
        else if(JPubUtils.IsNotEmpty(paras.getContactnumber())){
            ConContact contact=conContactMapper.selectById(paras.getContactnumber());
            stopkey=contact.getPhone();
        }
        FiStopcall fiStopcall=selectJoinOne(FiStopcall.class,
                new MPJLambdaWrapper<FiStopcall>()
                        .eq(FiStopcall::getStopkey,stopkey)
                        .eq(FiStopcall::getStoptype,paras.getStoptype())
                        .in(FiStopcall::getStatus,EnumConfirmStatus.New.value,
                                EnumConfirmStatus.Pending.value,
                                EnumConfirmStatus.Pass.value)
        );
        //相同的案件或号码正在审核中
        if(fiStopcall!=null) {
            if (fiStopcall.getStatus() == EnumConfirmStatus.Pending.value) {
                throw new ServiceException(EnumRCode.DataPending.value, EnumRCode.DataPending.name);
            }
            else if(fiStopcall.getStatus() == EnumConfirmStatus.New.value ||
                    fiStopcall.getStatus() == EnumConfirmStatus.Pass.value){
                throw new ServiceException(EnumRCode.DataProcess.value, EnumRCode.DataProcess.name);
            }
        }
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_STOPCALL"; //此任务是系统配置任务，不能delete
        }

        Integer wfid=cpCalllistService.getCalllistWfID(clid);

        Integer tasknumber=0;
        //CAMPAIGN.CHANNEL=10停催
        if(JPubUtils.IsNotEmpty(paras.getFicaseid())) { //从客户信息处添加，没有案件时，不关联催记
            tasknumber = fiTaskService.addTask($usrid, clid, paras.getFicaseid(),
                    EnumFiChannel.StopCall.value,
                    paras.getContactnumber(), stopkey,null,paras.getStoptype()+"停催："+paras.getApplydsc()
            );
        }

        int ret=0;
        log.info("applyAdd:clid={},stopkey={},tasknumber={},wfid={}",clid,stopkey,tasknumber,wfid);

        int stopid=0;
        FiStopcall fi = new FiStopcall();
        fi.setStopkey(stopkey);
        fi.setStoptype(paras.getStoptype());
        fi.setClid(clid);
        fi.setStopdays(paras.getStopdays());
        fi.setReason(paras.getReason());
        fi.setFicaseid(paras.getFicaseid());
        fi.setApplydsc(paras.getApplydsc());
        fi.setStopenddt(JPubUtils.addDays(new Date(), paras.getStopdays()));
        if(tasknumber>0) {//0或null，不写入，2024-12-27
            fi.setTasknumber(tasknumber);
        }
        fi.setApplyusr($usrid);
        fi.setApplydt(new Date());
        fi.setStatus(EnumConfirmStatus.New.value); //新建
        if(fiStopcall!=null) {
            stopid=fiStopcall.getStopid();
            //这里要主要update后，stopid不会反写到实体类里面
            ret=baseMapper.update(fi,new UpdateWrapper<FiStopcall>()
                    .lambda()
                    .eq(FiStopcall::getStopid,stopid)
                    .set(FiStopcall::getConfirmdsc,null)
                    .set(FiStopcall::getConfirmdt,null)
                    .set(FiStopcall::getConfirmusr,null)
                    .set(FiStopcall::getClosedsc,null)
                    .set(FiStopcall::getClosedt,null)
                    .set(FiStopcall::getCloseusr,null)
            );
        }
        else{
            fi.setCrdt(new Date());
            fi.setCrusr($usrid);
            ret=baseMapper.insert(fi);

            stopid=fi.getStopid();
        }

        if(wfid>0){
            //wfid=0 表示此任务clid没有配置工作流，前台可以根据是否有wfid显示不通的审批流程或状态
            String status=fiWorkFlowCase.doCreate($usrid,wfid,stopid,tasknumber);
            fi = new FiStopcall();
            fi.setStopid(stopid);
            fi.setStatus(Integer.parseInt(status)); //处理中
            baseMapper.updateById(fi);
        }

        return new CmdResVo(ret,Integer.toString(fi.getStopid()));
    }

    @Override
    public CmdResVo fiStopCallCancel(String $usrid, FiApplyCancelVo paras)
    {
        FiStopcall fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())){
            fiTaskService.updateStatus(fi.getTasknumber(),$usrid,"X");
        }
        else{
            log.warn("applyCancel.getTasknumber.isnull");
        }
        Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
        if(wfid>0){//有工作流,取消
            fiWorkFlowCase.doCancel($usrid,wfid,fi.getStopid());
        }

        fi = new FiStopcall();
        fi.setStopid(paras.getApplynumber());
        fi.setStatus(EnumConfirmStatus.Cancel.value); //取消
        fi.setCloseusr($usrid);
        fi.setClosedt(new Date());
        fi.setClosedsc(EnumConfirmStatus.Cancel.name);
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,fi.getStopid().toString());
    }

    @Override
    public CmdResVo fiStopCallEnd(String $usrid, FiApplyCancelVo paras)
    {
        FiStopcall fi = baseMapper.selectById(paras.getApplynumber());
        fi.setStatus(EnumConfirmStatus.Stop.value); //终止
        fi.setCloseusr($usrid);
        fi.setClosedt(new Date());
        fi.setClosedsc(EnumConfirmStatus.Stop.name);
        int ret=baseMapper.updateById(fi);

        if(JPubUtils.IsNotEmpty(fi.getFicaseid())&&
                JPubUtils.IsEqual(fi.getStoptype(),"CASE")) {
            SetFiCaseStopCallEnd($usrid, fi.getFicaseid());
        }

        return new CmdResVo(ret,fi.getStopid().toString());
    }

    @Override
    public CmdResVo fiStopCallConfirm(String $usrid, FiApplyConfirmVo paras)
    {
        boolean confirmend=true;
        String okstatus=paras.getActionid().toString();
        FiStopcall fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(paras.getCaseactid())){
            //需要走工作流
            WfNextStepVo wfNextStepVo=fiWorkFlowCase.doExec($usrid,paras.getCaseactid(),
                    paras.getActionid(),paras.getWfcaseid(),paras.getConfirmdsc()
            );
            okstatus=wfNextStepVo.getStatus();

            //可能有多级审核,3=审核全部完成
            if(!JPubUtils.IsEqual(wfNextStepVo.getType(), EnumWorkFlowStep.End.value)) {
                confirmend=false;
            }
        }
        else{
            Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
            if(wfid==null||wfid==0){//不使用工作流,这种情况下okstatus就是字典ID，直接写审核结果
                log.info("fiStopCallConfirm.nouse workflow：okstatus={}",okstatus);
            }
            else{//可能配置错误或网络引起的，2024-08-29
                log.warn("fiStopCallConfirm.nofind wf caseactid.");
                throw new ServiceException(EnumRCode.WfDataErr.value, EnumRCode.WfDataErr.name);
            }
        }

        //单纯就是审批流程，结果后续操作就在这里写，如果有后续反馈的，在result里面写，比如外访
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())&&confirmend) {
            fiTaskService.updateStatus(
                    fi.getTasknumber(),
                    $usrid,
                    fiWorkFlowCase.getPassStatus(okstatus)
            );
            if(JPubUtils.IsEqual(okstatus,EnumConfirmStatus.Pass.value)&&
                    JPubUtils.IsEqual(fi.getStoptype(),"CASE")) {//审核通过
                SetFiCaseStopCall($usrid,fi.getFicaseid());
            }
        }

        int ret=0;
        if(JPubUtils.IsNotEmpty(okstatus)){
            fi = new FiStopcall();
            fi.setStopid(paras.getApplynumber());
            fi.setStatus(Integer.parseInt(okstatus));
            fi.setConfirmusr($usrid);
            fi.setConfirmdt(new Date());
            fi.setConfirmdsc(paras.getConfirmdsc());
            ret=baseMapper.updateById(fi);
        }

        return new CmdResVo(ret,paras.getApplynumber().toString());
    }

    @Override
    public CmdResVo fiStopCallEndList(String $usrid, List<String> paras)
    {
        for(String id : paras) {
            FiStopcall fi =baseMapper.selectById(Integer.parseInt(id));
            fi.setStatus(EnumConfirmStatus.Stop.value); //终止
            fi.setCloseusr($usrid);
            fi.setClosedt(new Date());
            fi.setClosedsc(EnumConfirmStatus.Stop.name);
            baseMapper.updateById(fi);
            if(JPubUtils.IsNotEmpty(fi.getFicaseid())&&
                    JPubUtils.IsEqual(fi.getStoptype(),"CASE")) {
                SetFiCaseStopCallEnd($usrid, fi.getFicaseid());
            }
        }
        return new CmdResVo(paras.size());
    }

    private int updateStopCall(String $usrid,String stopkey,String stoptype,Integer stopdays,String reason,String applydsc)
    {
        int ret=0;
        boolean isupdate=true;
        if(JPubUtils.IsEmpty(stopkey)){
            log.warn("updateStopCall:keyval isnull");
            return 0;
        }
        //2024-06-26 edit in
        FiStopcall fiStopcall=selectJoinOne(FiStopcall.class,
                new MPJLambdaWrapper<FiStopcall>()
                        .eq(FiStopcall::getStopkey,stopkey)
                        .eq(FiStopcall::getStoptype,stoptype)
                        .in(FiStopcall::getStatus,EnumConfirmStatus.New.value,
                                EnumConfirmStatus.Pending.value,
                                EnumConfirmStatus.Pass.value)
        );
        if(fiStopcall==null){
            isupdate=false;
        }
        fiStopcall=new FiStopcall();
        fiStopcall.setStatus(EnumConfirmStatus.Pass.value);
        fiStopcall.setApplydt(new Date());
        fiStopcall.setApplyusr($usrid);
        fiStopcall.setReason(reason);
        fiStopcall.setStoptype(stoptype);
        fiStopcall.setStopdays(stopdays);
        fiStopcall.setStopenddt(JPubUtils.addDays(new Date(), stopdays));
        fiStopcall.setApplydsc(applydsc);
        fiStopcall.setConfirmdt(new Date());
        fiStopcall.setConfirmusr($usrid);
        fiStopcall.setConfirmdsc("批量停催");
        if(JPubUtils.IsEqual(stoptype,"CASE")){//2024-07-09
            fiStopcall.setFicaseid(JPubUtils.StrDateToInt(stopkey));
        }
        if(!isupdate){
            fiStopcall.setStopkey(stopkey);
            fiStopcall.setCrdt(new Date());
            fiStopcall.setCrusr($usrid);
            ret=baseMapper.insert(fiStopcall);
        }
        else{
            ret=baseMapper.update(fiStopcall,new UpdateWrapper<FiStopcall>()
                        .lambda()
                        .eq(FiStopcall::getStopid,fiStopcall.getStopid())
                        .set(FiStopcall::getClosedsc,null)
                        .set(FiStopcall::getClosedt,null)
                        .set(FiStopcall::getCloseusr,null)
                );
        }

        return ret;
    }

    @Override
    public CmdResVo fiStopCallListAdd(String $usrid, StopCallListVo paras)
    {
        int ret=0;
        for(String phone : paras.getPhonelist()) {
            if(paras.getIsstopcall()==1) {
                updateStopCall($usrid, phone.trim(),"CALL",
                        paras.getStopdays(),paras.getReason(),paras.getApplydsc());
            }
            if(paras.getIsstopsms()==1){
                updateStopCall($usrid, phone.trim(),"SMS",
                        paras.getStopdays(),paras.getReason(),paras.getApplydsc());
            }
            ret++;
        }
        return new CmdResVo(ret);
    }

    @Override
    public CmdResVo fiStopCaseListAdd(String $usrid, StopCaseListVo paras)
    {
        int ret=0;
        for(String ficaseid : paras.getCaselist()) {
            if(JPubUtils.IsEmpty(ficaseid)) continue;

            int caseid=Integer.parseInt(ficaseid);

            Integer tasknumber=fiTaskService.addTask($usrid,"SYS_STOPCALL",caseid,
                    EnumFiChannel.StopCall.value,null,null,null,"CASE批量停催："+paras.getApplydsc()
            );

            updateStopCall($usrid, ficaseid.trim(),"CASE",
                    paras.getStopdays(),paras.getReason(),paras.getApplydsc());

            SetFiCaseStopCall($usrid,caseid);

            fiTaskService.updateStatus(
                    tasknumber,
                    $usrid,
                    fiWorkFlowCase.getPassStatus(String.format("%d",EnumConfirmStatus.Pass.value))
            );

            ret++;
        }
        return new CmdResVo(ret);
    }

    private void SetFiCaseStopCall(String $usrid,Integer ficaseid)
    {
        FiCreditcases fi=fiCreditcasesMapper.selectById(ficaseid);
        fi.setCreditcaseid(ficaseid);
        fi.setCcc(EnumFiCaseQueue.S.name);
        fi.setMddt(new Date());
        fi.setMdusr($usrid);
        fiCreditcasesMapper.updateById(fi);
    }

    private void SetFiCaseStopCallEnd(String $usrid,Integer ficaseid)
    {
        FiCreditcases fi=fiCreditcasesMapper.selectById(ficaseid);
        fi.setCreditcaseid(ficaseid);
        Integer status=fi.getStatus();
        if(status==0||status==3||status==4) {
            fi.setCcc(EnumFiCaseQueue.O.name);
        }
        else if(status==1||status==2){
            fi.setCcc(EnumFiCaseQueue.Q.name);
        }
        else if(status==9){
            fi.setCcc(EnumFiCaseQueue.R.name);
        }
        fi.setMddt(new Date());
        fi.setMdusr($usrid);
        fiCreditcasesMapper.updateById(fi);
    }
}




